<?php
namespace Addons\UserCenter\Controller;

use Home\Controller\AddonsController;
use User\Api\UserApi;

class UserCenterController extends AddonsController
{


    Public function _initialize()
    {

        $controller = strtolower(_ACTION);

        $res ['title'] = '用户中心';
        $res ['url'] = addons_url('UserCenter://UserCenter/lists');
        $res ['class'] = $controller == 'lists' ? 'current' : '';
        $nav [] = $res;

        $res ['title'] = '功能配置';
        $res ['url'] = addons_url('UserCenter://UserCenter/config');
        $res ['class'] = $controller == 'config' ? 'current' : '';
        $nav [] = $res;

        $this->assign('nav', $nav);
    }

    /**
     * 显示微信用户列表数据
     */
    public function lists()
    {

        //覆盖删除按钮
        $this->assign("delete", "拉取粉丝");
        $this->assign("add_button", false);
        $this->assign("del_url", addons_url("UserCenter://UserCenter/getfanse"));
        $this->assign("re_url", addons_url("UserCenter://UserCenter/lists"));
        $this->assign("updatefanse", rtrim(addons_url("UserCenter://UserCenter/updatefanse"), "'.html'"));
        $model = $this->getModel('follow');

        parent::common_lists($model, 0, '', 'subscribe_time desc');
    }

    // 用户绑定
    public function edit()
    {
        $is_admin_edit = false;
        if (!empty($_REQUEST['id'])) {
            $map['id'] = intval($_REQUEST['id']);
            $is_admin_edit = true;
            $msg = '编辑';
            $html = 'edit';
        } else {
            $msg = '绑定';
            $openid = $map ['openid'] = get_openid();
            $html = 'moblieForm';
        }
        $token = $map ['token'] = get_token();
        $model = $this->getModel('follow');

        if (IS_POST) {
            $is_admin_edit && $_POST['status'] = 2;
            $Model = D(parse_name(get_table_name($model ['id']), 1));
            // 获取模型的字段信息
            $Model = $this->checkAttr($Model, $model ['id']);
            if ($Model->create() && $Model->where($map)->save()) {
                //lastsql();exit;
                $url = '';
                $bind_backurl = cookie('__forward__');
                $config = getAddonConfig('UserCenter');
                $jumpurl = $config['jumpurl'];

                if (!empty($bind_backurl)) {
                    $url = $bind_backurl;
                    cookie('__forward__', NULL);
                } elseif (!empty($jumpurl)) {
                    $url = $jumpurl;
                } elseif (!$is_admin_edit) {
                    $url = addons_url('WeiSite://WeiSite/index', $map);
                }

                $this->success($msg . '成功！', $url);
            } else {
                //lastsql();
                //dump($map);exit;
                $this->error($Model->getError());
            }
        } else {
            $fields = get_model_attribute($model ['id']);
            if (!$is_admin_edit) {
                $fieldArr = array('nickname', 'sex', 'mobile'); //headimgurl
                foreach ($fields[1] as $k => $vo) {
                    if (!in_array($vo['name'], $fieldArr))
                        unset($fields[1][$k]);
                }
            }

            // 获取数据
            $data = M(get_table_name($model ['id']))->where($map)->find();

            $token = get_token();
            if (isset ($data ['token']) && $token != $data ['token'] && defined('ADDON_PUBLIC_PATH')) {
                $this->error('非法访问！');
            }

            // 自动从微信接口获取用户信息
            empty($openid) || $info = getWeixinUserInfo($openid, $token);
            if (is_array($info)) {
                if (empty ($data ['headimgurl']) && !empty ($info ['headimgurl'])) {
                    // 把微信头像转到WeiPHP的通用图片ID保存 TODO
                    $data ['headimgurl'] = $info ['headimgurl'];
                }
                $data = array_merge($info, $data);
            }

            $this->assign('fields', $fields);
            $this->assign('data', $data);
            $this->meta_title = $msg . '用户消息';

            $this->assign('post_url', U('edit'));

            $this->display($html);
        }


    }

    public function userCenter()
    {
        $openid = $_GET['openid'];
        $token = $_GET['token'];

        $m = M('follow');
        $where['openid'] = $openid;
        $where['token'] = $token;
        $user = $m->where($where)->find();
        $Dao = M();
        //或者使用 $Dao = new Model();
        $list = $Dao->query("select t.title ,sum(t.score) score from(
select  conf.title as title,credit.score as score from wp_credit_config conf
left join wp_credit_data credit on conf.name = credit.credit_name
where credit.uid='".$user['id']."'
) t
group by t.title");

        $this->assign("user", $user);
        $this->assign("scorelog",$list);
        $this->display();

    }


    // 拉取粉丝方法
    public function getfanse()
    {
        $access_token = get_access_token();
        $token = get_token();
        $next_openid = "";
        $m = M('follow');
        do {
            $url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=$access_token";
            if ($next_openid != "") {
                $url = $url . "&next_openid=$next_openid";
            }

            $content = file_get_contents($url);
            $content = json_decode($content, true);
            $next_openid = $content['next_openid'];
            $data = $content['data']['openid'];
            for ($i = 0; $i < count($data); $i++) {
                $openid = $data[$i];
                $where['openid'] = array('eq', $openid);
                $follow = $m->where($where)->find();
                if (!$follow) {
                    $member['openid'] = $openid;
                    $member['token'] = $token;
                    $m->add($member);
                }
            }
        } while ($next_openid != "");
        $this->success("粉丝openid拉取完毕！");
    }

    //更新粉丝信息
    public function updatefanse()
    {
        $m = M('follow');
        $page = $_GET['page'];
        $token = get_token();
        $access_token = get_access_token();
        $where['token'] = $token;
        $total = $m->where($where)->count();
        $member = $m->order('id desc')->limit($page*100, ($page + 1)*100)->select();
        $url="https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token=$access_token";
        $postdata=array(
            "user_list"=>array(
            )
        );

        for($i=0;$i<count($member);$i++){
            $postdata['user_list'][]=array(
                'openid'=>$member[$i]['openid'],
                'lang'=>"zh-CN"
            );
        }
        $datas=curlPost($url,json_encode($postdata));
        $infodatas=json_decode($datas,true)['user_info_list'];
        $db = M('follow');
        $wh['token']=get_token();
        for($i=0;$i<count($infodatas);$i++){
            if($infodatas[$i]['subscribe']==1){
                $wh['openid']=$infodatas[$i]['openid'];
                $user=$db->where($wh)->find();
                if($user){
                    $user['nickname'] = $infodatas[$i]['nickname'];
                    $user['sex'] = $infodatas[$i]['sex'];
                    $user['language'] = $infodatas[$i] ['language'];
                    $user['city'] = $infodatas[$i]['city'];
                    $user['province'] = $infodatas[$i]['province'];
                    $user['country'] = $infodatas[$i]['country'];
                    $user['headimgurl'] = $infodatas[$i]['headimgurl'];
                    $user['subscribe_time'] = $infodatas[$i]['subscribe_time'];
                    $db->save($user);
                }
            }
        }
        $baifenbi = (($page + 1)*100 / $total) * 100;
        $valeu = array(
            "total" => $total,
            "page" => $page,
            "baifen" => ceil($baifenbi)

        );
        $this->ajaxReturn($valeu, 'JSON');

    }

    function config()
    {
        // 使用提示
        $normal_tips = '如需用户关注时提示先绑定，请进入‘欢迎语’插件按提示进行配置提示语';
        $this->assign('normal_tips', $normal_tips);

        parent::config();
    }
}
